// pages/join/index.js
var userInfo = wx.getStorageSync('userInfo');
var url = getApp().globalData.ApiUrl;
var timeformat = require('../../utils/timeformat.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // avatar: userInfo.avatar,
    goods_details: {}, //商品详情
    pintuan_info: {}, //拼团详情
    hr: '',   //小时
    min: '', //分钟
    sec: '', //秒钟
    showPin: false, //底部弹窗
    goods_price: 0,
    count: 0,
    needLeave: false
  },
  /** 
   * 需要一个目标日期，初始化时，先得出到当前时间还有剩余多少秒
   * 1.将秒数换成格式化输出为XX天XX小时XX分钟XX秒 XX
   * 2.提供一个时钟，每10ms运行一次，渲染时钟，再总ms数自减10
   * 3.剩余的秒次为零时，return，给出tips提示说，已经截止
   */
  count_down: function (allsec) {
    var that = this;
    clearTimeout(that.data.timer);
    that.setData({
      day: timeformat.timeformat(allsec).days + '天',
      hr: timeformat.timeformat(allsec).hrs,
      min: timeformat.timeformat(allsec).mins,
      sec: timeformat.timeformat(allsec).second
    });
    if (allsec <= 0) {
      that.setData({
        day: '0天',
        hr: '00',
        min: '00',
        sec: '00'
      });
      // timeout则跳出递归
      return;
    };
    that.data.timer = setTimeout(function () {
      // 放在最后--
      allsec -= 1000;
      that.count_down(allsec);
    }, 1000);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {  
    var that = this; 
    var key = wx.getStorageSync('key');
    if (!key) {
      wx.navigateTo({
        url: '/pages/authorize/index',
      });
    };
    // 付款后，拼团详情信息接口
    wx.request({
      url: url + '/mobile/index.php?act=pintuan&op=info',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'GET',
      data: {
        key: wx.getStorageSync('key'),
        buyer_id: options.buyer_id,
        pintuan_id: options.log_id,
      },
      success: (res)=>{
        if(res.data.code == 200){
          var pintuan_info = res.data.datas.pintuan_info;
          var now = pintuan_info.log_list;
          var count = pintuan_info.num;
          var avatar = pintuan_info.log_list[0].avatar;
          var tim = pintuan_info.pintuan_end_time * 1000;
          var once = new Date().getTime();
          that.count_down(tim);
          var aImg = [];
          for (var i in now) {
            aImg.push(now[i].avatar);
          };
          if (now.length != pintuan_info.min_num) {
            that.setData({
              needLeave: false
            })
          } else {
            that.setData({
              needLeave: true
            }) 
          };
          if (pintuan_info.buyer_id) {
            that.setData({
              buyer_id: pintuan_info.buyer_id,
            });
          };
          if (pintuan_info.log_id) {
            that.setData({
              log_id: pintuan_info.log_id,
            });
          };
          that.setData({
            pintuan_info: pintuan_info,
            goods_id: pintuan_info.goods_id,
            count: count,
            avatar: avatar,
            aImg: aImg,
            now: now
          });
          that.goodsDetails(that.data.goods_id);
        } else {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
        }
      },
      fail: () => {
        wx.showToast({
          title: '人太多啦',
          icon: 'none',
          duration: 2000
        })
      }
    });
    that.getMusicInfo();
  },
  // 获取商城优惠列表
  getMusicInfo: function () {
    var that = this;
    wx.request({
      url: url + '/mobile/index.php?act=api&op=get_kanjia_list',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'GET',
      success: (res) => {
        if (res.data.code == 200) {
          var goodsRecmd = res.data.datas;
          that.setData({
            goodsRecmd: goodsRecmd
          });
        } else {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          }
          wx.showToast({
            title: res.data.datas.error,
            icon: 'none',
            duration: 1500,
            mask: true
          })
        }
      }
    })
  },
  /**
   * 获取商品详情
   */
  goodsDetails: function (goods_id){
    var that = this;
    wx.showLoading({
      title: '加载中，请稍后...',
    })
    //获取商品详情
    wx.request({
      url: url + '/mobile/index.php?act=goods&op=goods_detail',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'GET',
      data: {
        goods_id: goods_id
      },
      success: (res) => {
        if (res.data.code == 200) {
          wx.hideLoading();
          var datas = res.data.datas;
          var specObj = res.data.datas.goods_info.spec_name;
          var imgURL = res.data.datas.goods_image.split(',');
          var tmp = {}; //商品规格
          var tmp2 = {}; //商品尺寸
          var specALLArr = []; // 商品贵和和商品
          for (var i in specObj) {
            tmp.id = i;
            tmp.name = specObj[i];
            tmp.twoData = [];
            for (var j in res.data.datas.goods_info.spec_value[i]) {
              tmp2.id = j;
              tmp2.name = res.data.datas.goods_info.spec_value[i][j];
              tmp2.propertyID = i;
              tmp.twoData.push(JSON.parse(JSON.stringify(tmp2)));
            }
            specALLArr.push(JSON.parse(JSON.stringify(tmp)));
          };
          if (datas.goods_info.kanjia_promotion == 1) {
            that.setData({
              imgUrl: imgURL,
              sum: imgURL.length,
              goods_details: res.data.datas,
              specALLArr: specALLArr,
              buyGoods_id: goods_id, //购买的商品id
              goods_price: datas.goods_info.kanjia_price, //砍价价格
              goods_storage: datas.goods_info.goods_storage, //商品库存
            });
          } else if (datas.goods_info.pintuan_promotion == 1) {
            that.setData({
              imgUrl: imgURL,
              sum: imgURL.length,
              goods_details: res.data.datas,
              specALLArr: specALLArr,
              buyGoods_id: goods_id, //购买的商品id
              goods_price: datas.goods_info.pintuan_price, //砍价价格
              goods_storage: datas.goods_info.goods_storage, //商品库存
            });
          } else {
            that.setData({
              imgUrl: imgURL,
              sum: imgURL.length,
              goods_details: res.data.datas,
              specALLArr: specALLArr,
              buyGoods_id: goods_id, //购买的商品id
              goods_price: datas.goods_info.goods_price, //砍价价格
              goods_storage: datas.goods_info.goods_storage, //商品库存
            });
          }
        } else {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
        };
      },
      fail: ()=> {
        wx.showToast({
          title: '人太多啦',
          icon: 'none',
          duration: 1500
        })
      }
    }); 
  },
  /**
   * 我要砍
   */
  toBargain: function (e) {
    var that = this;
    var dataset = e.currentTarget.dataset;
    var goods_img = e.currentTarget.dataset.goods_img;
    that.setData({
      showView: true,
      goods_img: goods_img
    });
    that.goodsDetails(dataset.goods_id);
  },
  /**
   * 切换规格选中状态
   * @author chelfinn
   * @date 2018-09-18
   */
  clickTap: function (e) {
    var that = this;
    var specALLArr = that.data.specALLArr;
    var childs = that.data.specALLArr[e.currentTarget.dataset.propertyindex].twoData;
    // 取消该分类下的子栏目所有的选中状态
    for (var i = 0; i < childs.length; i++) {
      that.data.specALLArr[e.currentTarget.dataset.propertyindex].twoData[i].active = false;
    }
    // 设置当前选中状态
    that.data.specALLArr[e.currentTarget.dataset.propertyindex].twoData[e.currentTarget.dataset.propertychildindex].active = true;
    that.setData({
      specALLArr: specALLArr
    });

    // 循环数组 获取点中状态时的规格
    for (var id in specALLArr) {
      for (var i in specALLArr[id].twoData) {
        if (specALLArr[id].twoData[i].active == true) {
          ids.push(specALLArr[id].twoData[i].id);  // 获取的商品选中时的id
          valus.push(specALLArr[id].twoData[i].name);   // 获取商品点中时的规格
        }
      };
    };
    var spec_id = ids.sort().join("|");   // 升序
    var spec_value = valus.toString().replace(/,/g, " ");  // 选中的规格
    var spec_list = that.data.detailData.spec_list;
    if (spec_value) {
      this.setData({
        propertyChildNames: spec_value,
      })
    }
    if (spec_id in spec_list) {
      that.setData({
        buyGoods_id: spec_list[spec_id], //获取购买的商品id
      });
    }
  },
  /**
   * 跳转商品详情
   */
  toDetailTap: function (e) {
    var goods_id = e.currentTarget.dataset.goods_id;
    wx.navigateTo({
      url: '/pages/group-detail/index?goods_id=' + goods_id,
    });
  },
  /**
   * 立即购买
   */
  groupBuyNow: function (e) {
    var that = this;
    /**
     * log_id 参团id,自己发起的团,支付成功后返回的id，有则传，无则不传，不能穿空    pintuan_id 不为空时，为拼主的拼团号
     * pintuan    拼团的话设置为1，默认为空
     * status 1普通购买，2拼团，3秒杀
     */
    var ifcart = '';
    var log_id = '';
    var goods_id = e.currentTarget.dataset.goods_id;
    //item 店铺名，商品名，商品图片，选中规格，商品单价，数量
    var item = {};
    item.store_name = that.data.goods_details.store_info.store_name;
    item.store_id = that.data.goods_details.store_info.store_id;
    item.goods_name = that.data.goods_details.goods_info.goods_name;
    item.goods_price = that.data.goods_price;
    item.goods_num = that.data.num;
    item.spec_name = that.data.propertyChildNames;
    item = JSON.stringify(item);
    var totalPrice = that.data.goods_price;
    var cart_id = goods_id + '|1';

    var item1 = JSON.parse(item);
    var storega = that.data.goods_storage;
    if (item1.spec_name) {
      var arr = item1.spec_name.split(" ");
    };
    if (this.data.specALLArr.length == 0) {
      if (storega == 0) {
        wx.showModal({
          title: '提示',
          content: '库存不足，请购买其他商品',
          showCancel: false,
        })
        this.setData({
          showView: false
        })
        return;
      }
      if (that.data.goods_details.goods_info.kanjia_promotion == 1) {
        var is_kanjia = that.data.goods_details.goods_info.kanjia_promotion;
        wx.navigateTo({
          url: '/pages/submit-order/index?status=1&cart_id=' + cart_id + '&ifcart=' + ifcart + '&is_kanjia=' + is_kanjia,
        });
      };
      if (that.data.goods_details.goods_info.pintuan_promotion == 1) {
        var is_pintuan = that.data.goods_details.goods_info.pintuan_promotion;
        wx.navigateTo({
          url: '/pages/submit-order/index?status=1&cart_id=' + cart_id + '&ifcart=' + ifcart + '&is_pintuan=' + is_pintuan + '&buyer_id=' + that.data.buyer_id + '&log_id=' + that.data.log_id,
        });
      };
      
    } else {
      if (storega == 0) {
        wx.showModal({
          title: '提示',
          content: '库存不足，请购买其他上商品',
          showCancel: false,
        })
        this.setData({
          showView: false
        })
        return;
      }
      if (arr.length != this.data.specALLArr.length) {
        wx.showModal({
          title: '提示',
          content: '请先选择商品规格尺寸哟~',
          showCancel: false,
        })
        return;
      }
    }
  },
  /**
   * 加入其它团
   */
  toJoinOther: function (e){
    var goods_id = e.currentTarget.dataset.goods_id;
    wx.navigateTo({
      url: '/pages/group-detail/index?goods_id=' + goods_id,
    })
  },
  /**
   * 我要参团
   */
  toJoinGroup: function (e){
    var that = this;
    var goods_id = e.currentTarget.dataset.goods_id;
    that.setData({
      showView: true,
    });
    that.goodsDetails(goods_id);  
  },
  /**
   * 参团--提交订单
   */
  groupNow: function (e) {
    var that = this;
    /**
     * log_id 参团id,自己发起的团,支付成功后返回的id，有则传，无则不传，不能穿空    pintuan_id 不为空时，为拼主的拼团号
     * pintuan    拼团的话设置为1，默认为空
     * status 1普通购买，2拼团，3秒杀
     */
    if (that.data.goods_details.goods_info.pintuan_promotion == 1) {
      var is_pintuan = that.data.goods_details.goods_info.pintuan_promotion;
    };
    var ifcart = '';
    // if (that.data.pin_item.log_id) {
    //   var log_id = that.data.pin_item.log_id;
    // }
    var goods_id = e.currentTarget.dataset.goods_id;
    var item = {};
    //item 店铺名，商品名，商品图片，选中规格，商品单价，数量
    var item = {};
    item.store_name = that.data.goods_details.store_info.store_name;
    item.goods_name = that.data.goods_details.goods_info.goods_name;
    item.goods_price = that.data.goods_details.goods_info.pintuan_price;
    item.spec_name = that.data.propertyChildNames;
    item.goods_num = 1;
    item = JSON.stringify(item);
    var totalPrice = e.currentTarget.dataset.pintuan_price;
    var cart_id = goods_id + '|1';
    wx.navigateTo({
      url: '/pages/submit-order/index?status=2&cart_id=' + cart_id + '&ifcart=' + ifcart + '&is_pintuan=' + is_pintuan + '&buyer_id=' + that.data.buyer_id + '&log_id=' + that.data.log_id,
    });
  },
  /**
   * 关闭弹窗
   */
  errorTap: function () {
    this.setData({
      showPin: false,
      showView: false,
      propertyChildNames: '',
    });
  },
  // 跳转去首页
  toIndex: function() {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})